<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { axiosrnewmedical } from '@/http/axiosRead';

const router = useRouter();
const searchValue = ref('');
const loading = ref(false);
const finished = ref(false);
interface ServiceType {
  id: number;
  name: string;
  deptId: number;
  deptName: string;
  doctorLevel: string;
  remark: string;
}

interface PriceItem {
  id: number;
  typeId: number;
  typeName: string;
  serviceName: string;
  priceMin: number;
  priceMax: number;
  promoText: string;
  updatedAt: string;
  categoryTag: string;
  specs?: string;
  manufacturer?: string;
  isInsurance?: boolean;
}

const serviceTypes = ref<ServiceType[]>([]);
const priceItems = ref<PriceItem[]>([]);
const activeType = ref<number | string>(0);
const showFilter = ref(false);
const showTypePopup = ref(false);
const selectedType = ref('');
const currentTypeId = ref<number | null>(null);

// 筛选条件
const filterOptions = reactive({
  deptId: '', // 默认科室ID
  doctorLevel: "" // 默认医生级别
});

// 获取价格服务类型列表
const getServiceTypes = async () => {
  try {
    loading.value = true;
    const response = await axiosrnewmedical.get('/Price/service-types', {
      params: {
        deptId: filterOptions.deptId,
        doctorLevel: filterOptions.doctorLevel
      }
    });
    
    if (response.data.code === 200) {
      serviceTypes.value = response.data.data;
      // 初始化时获取所有类型的价格条目
      getPriceItems(); // 不传typeId，获取所有类型的价格条目
      selectedType.value = '全部类型';
    }
  } catch (error) {
    console.error('获取价格服务类型列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 获取价格条目列表
const getPriceItems = async (typeId?: number) => {
  try {
    loading.value = true;
    finished.value = false;
    currentTypeId.value = typeId || null;
    
    // 当typeId为undefined或0时，不传typeId参数，获取所有类型的价格条目
    const params: { typeId?: number } = {};
    if (typeId && typeId > 0) {
      params.typeId = typeId;
    }
    
    const response = await axiosrnewmedical.get('/Price/items', { params });
    
    if (response.data.code === 200) {
      priceItems.value = response.data.data;
    }
  } catch (error) {
    console.error('获取价格条目列表失败:', error);
  } finally {
    loading.value = false;
    finished.value = true;
  }
};

  // 搜索价格条目
const onSearch = () => {
  // 实际应用中可根据后端接口调整搜索逻辑
  if (searchValue.value.trim()) {
    // 这里可以调用搜索API，目前仅做前端过滤演示
    // 将查询内容作为参数传递给后端，后端负责过滤
    getPriceItems(currentTypeId.value || 0);
  } else {
    // 如果搜索框为空，恢复原始列表
    if (activeType.value) {
      getPriceItems(Number(activeType.value));
    }
  }
};

// 已使用selectTypeItem替代此方法

// 格式化价格显示
const formatPrice = (min: number, max: number) => {
  if (min === max) {
    return `${min.toFixed(2)}(元)`;
  }
  return `${min.toFixed(2)}~${max.toFixed(2)}(元)`;
};

// 返回首页
const goBack = () => {
  router.push('/home');
};

// 选择全部类型
const selectAllTypes = () => {
  selectedType.value = '全部类型';
  showTypePopup.value = false;
  getPriceItems(); // 不传typeId，获取全部类型
};

// 选择具体类型
const selectTypeItem = (type: ServiceType) => {
  selectedType.value = type.name;
  showTypePopup.value = false;
  getPriceItems(type.id);
};

// 获取分类样式类
const getCategoryClass = (category: string) => {
  const categoryMap: { [key: string]: string } = {
    '药品': 'tag-medicine',
    '诊疗': 'tag-treatment', 
    '检查': 'tag-examination',
    '手术': 'tag-surgery',
    '护理': 'tag-nursing'
  };
  return categoryMap[category] || 'tag-default';
};

onMounted(() => {
  getServiceTypes();
});
</script>

<template>
  <div class="price-query-container">
    <!-- 导航栏 -->
    <van-nav-bar 
      title="价目查询" 
      left-arrow 
      @click-left="goBack" 
      fixed />
    
    <!-- 下拉框区域 -->
    <div class="dropdown-bar">
      <div class="dropdown-btn" @click="showTypePopup = true">
        <span class="dropdown-text">{{ selectedType || '全部类型' }}</span>
        <van-icon name="arrow-down" class="dropdown-icon" />
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-bar">
      <van-search
        v-model="searchValue"
        placeholder="可输入药品、项目内容"
        shape="round"
        @search="onSearch">
      </van-search>
    </div>

    <!-- 服务类型已改为顶部下拉菜单，这里不再需要 -->

    <!-- 价格列表 -->
    <div class="price-list">
      <van-empty v-if="priceItems.length === 0" description="暂无数据" />
      
      <div class="price-card" v-for="item in priceItems" :key="item.id">
        <div class="price-item">
          <div class="item-header">
            <div class="name-section">
              <h3 class="item-name">{{ item.serviceName }}</h3>
              <div class="category-tag" :class="getCategoryClass(item.categoryTag || item.typeName)">
                {{ item.categoryTag || item.typeName }}
              </div>
            </div>
          </div>
          
          <div class="price-section">
            <div class="price-main">
              <span class="price-icon">💰</span>
              <span class="price-value">{{ formatPrice(item.priceMin, item.priceMax) }}</span>
            </div>
          </div>
          
          <div class="info-section">
            <div class="info-item">
              <van-icon name="bookmark-o" class="info-icon" />
              <span class="info-text">{{ item.typeName || '药品' }}</span>
            </div>
            
            <div class="info-item" v-if="item.specs">
              <van-icon name="description-o" class="info-icon" />
              <span class="info-text">{{ item.specs }}</span>
            </div>
            
            <div class="info-item" v-if="item.manufacturer">
              <van-icon name="shop-o" class="info-icon" />
              <span class="info-text">{{ item.manufacturer }}</span>
            </div>
            
            <div class="info-item" v-if="item.isInsurance !== undefined">
              <van-icon name="medal-o" class="info-icon" />
              <span class="info-text insurance-text" :class="{ 'is-insurance': item.isInsurance }">
                {{ item.isInsurance ? '医保' : '自费' }}
              </span>
            </div>
          </div>
        </div>
      </div>
      
      <van-loading v-if="loading" class="loading" size="24px">加载中...</van-loading>
    </div>

    <!-- 底部加载更多区域 -->
    <div class="load-more" v-if="finished && priceItems.length > 0">
      <div class="load-more-text">已加载全部</div>
    </div>

    <!-- 筛选弹出层 -->
    <van-popup
      v-model:show="showFilter"
      position="bottom"
      round
      closeable
      close-icon-position="top-right"
      :style="{ height: '50%' }">
      <div class="filter-header">条件筛选</div>
      
      <div class="filter-content">
        <!-- 实际筛选内容可根据需求自行添加 -->
        <van-cell-group title="科室">
          <van-cell title="全部科室" is-link />
        </van-cell-group>
        
        <van-cell-group title="医生级别">
          <van-cell title="全部级别" is-link />
        </van-cell-group>
      </div>
      
      <div class="filter-footer">
        <van-button block type="primary" @click="showFilter = false">确认</van-button>
      </div>
    </van-popup>
    
    <!-- 类型选择弹出层 -->
    <van-popup
      v-model:show="showTypePopup"
      position="top"
      round
      :style="{ width: '120px', left: '16px', top: '108px', boxShadow: '0 2px 12px rgba(0, 0, 0, 0.15)' }">
      <div class="type-dropdown">
        <div class="type-item" @click="selectAllTypes">全部类型</div>
        <div 
          v-for="type in serviceTypes" 
          :key="type.id" 
          class="type-item"
          @click="selectTypeItem(type)">
          {{ type.name }}
        </div>
      </div>
    </van-popup>
  </div>
</template>

<style scoped>
.price-query-container {
  background-color: #f8f9fa;
  min-height: 100vh;
  padding-top: 46px;
}

.dropdown-bar {
  background-color: #fff;
  padding: 8px 16px;
  position: sticky;
  top: 46px;
  z-index: 10;
}

.dropdown-btn {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  padding: 10px 16px;
  border-radius: 12px;
  border: 1px solid #e8e8e8;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.2s ease;
  width: 120px;
}

.dropdown-btn:active {
  background-color: #f8f9fa;
  transform: scale(0.98);
}

.dropdown-text {
  font-size: 15px;
  color: #333;
  font-weight: 500;
}

.dropdown-icon {
  color: #999;
  transition: transform 0.2s ease;
  font-size: 14px;
}

.search-bar {
  background-color: #fff;
  padding: 12px 16px;
  position: sticky;
  top: 96px;
  z-index: 9;
}





.price-list {
  padding: 12px 16px;
  background: linear-gradient(135deg, #f5f7fa 0%, #f1f3f6 100%);
  min-height: calc(100vh - 200px);
}

.price-card {
  background: linear-gradient(135deg, #ffffff 0%, #fafbfc 100%);
  border-radius: 16px;
  margin-bottom: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;
}

.price-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.price-item {
  padding: 20px;
}

.item-header {
  margin-bottom: 16px;
}

.name-section {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
}

.item-name {
  font-size: 17px;
  font-weight: 600;
  color: #1a1a1a;
  line-height: 1.4;
  margin: 0;
  flex: 1;
}

.category-tag {
  font-size: 11px;
  font-weight: 500;
  padding: 4px 10px;
  border-radius: 12px;
  white-space: nowrap;
  flex-shrink: 0;
}

.tag-medicine {
  background: linear-gradient(135deg, #e8f5e8 0%, #d4edd4 100%);
  color: #2d8f2d;
  border: 1px solid #c3e6c3;
}

.tag-treatment {
  background: linear-gradient(135deg, #fff2e8 0%, #ffedd4 100%);
  color: #d46b08;
  border: 1px solid #ffd591;
}

.tag-examination {
  background: linear-gradient(135deg, #e6f7ff 0%, #d4edff 100%);
  color: #0958d9;
  border: 1px solid #91d5ff;
}

.tag-surgery {
  background: linear-gradient(135deg, #fff0f6 0%, #ffd6e7 100%);
  color: #c41d7f;
  border: 1px solid #ffadd2;
}

.tag-nursing {
  background: linear-gradient(135deg, #f6ffed 0%, #d9f7be 100%);
  color: #389e0d;
  border: 1px solid #b7eb8f;
}

.tag-default {
  background: linear-gradient(135deg, #f0f0f0 0%, #e8e8e8 100%);
  color: #666;
  border: 1px solid #d9d9d9;
}

.price-section {
  margin-bottom: 16px;
  padding: 16px;
  background: linear-gradient(135deg, #fff9f0 0%, #fff2e8 100%);
  border-radius: 12px;
  border: 1px solid #ffe7ba;
}

.price-main {
  display: flex;
  align-items: center;
  gap: 8px;
}

.price-icon {
  font-size: 20px;
}

.price-value {
  font-size: 22px;
  font-weight: bold;
  color: #ff6b35;
  text-shadow: 0 1px 3px rgba(255, 107, 53, 0.3);
}

.info-section {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: rgba(248, 250, 252, 0.8);
  border-radius: 8px;
  border: 1px solid #f0f2f5;
}

.info-icon {
  font-size: 14px;
  color: #8c8c8c;
  width: 16px;
  flex-shrink: 0;
}

.info-text {
  font-size: 14px;
  color: #595959;
  line-height: 1.4;
}

.insurance-text {
  font-weight: 500;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.insurance-text.is-insurance {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.insurance-text:not(.is-insurance) {
  background-color: #fff1f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

.loading {
  display: flex;
  justify-content: center;
  padding: 12px 0;
}

.filter-header {
  text-align: center;
  font-size: 16px;
  font-weight: bold;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.filter-content {
  padding: 0 16px;
  overflow-y: auto;
  max-height: calc(50vh - 120px);
}

.filter-footer {
  padding: 16px;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
}

.load-more {
  padding: 16px;
  text-align: center;
}

.load-more-text {
  color: #999;
  font-size: 14px;
}

.type-dropdown {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  animation: dropdown-appear 0.2s ease-out;
}

@keyframes dropdown-appear {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.type-item {
  padding: 14px 16px;
  font-size: 14px;
  color: #333;
  border-bottom: 1px solid #f2f2f2;
  text-align: center;
  position: relative;
}

.type-item:last-child {
  border-bottom: none;
}

.type-item:active {
  background-color: #e8f3ff;
  color: #338aff;
}


</style> 